import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Christian Dadswell
 * Date: 22/03/13
 * Time: 19:45
 */

// JSON METHODS
public class functions_Json {
    public static SimpleDateFormat standardDate = new SimpleDateFormat("ddMMyyyy");
    public static String standardDateAsString = standardDate.format(new Date());
    public static SimpleDateFormat bbcDate = new SimpleDateFormat("yyyyMMdd");
    public static String bbcDateAsString = bbcDate.format(new Date());
    public static SimpleDateFormat bbcUrlDate = new SimpleDateFormat("yyyy/MM/dd");
    public static String bbcUrlDateAsString = bbcUrlDate.format(new Date());

    // Method to create a json of stations* on the BBC and writes a json file. *National, Regional or Local
    public static boolean WriteStationsPerRegionToJson(HashMap mapFrom, String locality) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String stationJson;
        String jsonDirectory = constants.stationsDir;
        String jsonFileName = locality;

        stationJson = gson.toJson(mapFrom);
        WriteJSONFile(jsonDirectory, jsonFileName, stationJson);
        return true;
    }

    // This method gets all schedule dates and URLS for a given station and writes a json file.
    public static boolean WriteStationSchedulesPerStationToJson(String stationName, String stationScheduleUrl, HashMap mapScheduleUrls) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonDirectory = constants.schedulesStationsDir;
        String jsonFileName = functions_Strings.ReturnShortStationName(stationName);

        String jsonScheduleDatesUrls = gson.toJson(mapScheduleUrls);

        WriteJSONFile(jsonDirectory, jsonFileName, jsonScheduleDatesUrls);
        return true;
    }

    // This method gets all broadcasts for a given station and writes a json file.
    public static boolean WriteStationBroadcastsToJSON(String bbcStationName, String stationScheduleUrl, String scheduleDateSearched, String scheduleDate, String broadcastDurations,
                                                  String broadcastEpisodes, String broadcastTitles, String broadcastSubtitles, String broadcastSynopsis) {

        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonFinalString;
        String stationName = functions_Strings.ReturnShortStationName(bbcStationName);
        String jsonStationDirectory = constants.broadcastStationsDir + stationName + "\\";
        String jsonFileName = scheduleDateSearched;

        String jsonScheduleDate = "{" + gson.toJson("stationScheduleDate") + ":" + gson.toJson(scheduleDate) + ",";
        String jsonScheduleUrl = gson.toJson("stationScheduleUrl") + ":" + gson.toJson(stationScheduleUrl) + ",";
        String jsonDurations = gson.toJson("broadcastDurations") + ":" + gson.toJson(broadcastDurations) + ",";
        String jsonTitles = gson.toJson("broadcastTitles") + ":" + gson.toJson(broadcastTitles) + ",";
        String jsonSubtitles = gson.toJson("broadcastSubtitles") + ":" + gson.toJson(broadcastSubtitles) + ",";
        String jsonSynopsis = gson.toJson("broadcastSynopsis") + ":" + gson.toJson(broadcastSynopsis) + ",";
        String jsonEpisodeUrl = gson.toJson("broadcastEpisodeUrl") + ":" + gson.toJson(broadcastEpisodes) + "}}";

        jsonFinalString = jsonScheduleDate + jsonScheduleUrl + jsonDurations + jsonTitles + jsonSubtitles + jsonSynopsis + jsonEpisodeUrl;

        functions_fileio.CreateADirectory(jsonStationDirectory);
        WriteJSONFile(jsonStationDirectory, jsonFileName, jsonFinalString);
        return true;
    }

    // This method writes a json file from a string.
    public static boolean WriteJSONFile(String directoryToWriteFile, String jsonFileToWrite, String jsonToWrite) {

        try {
            FileWriter writer = new FileWriter(directoryToWriteFile + jsonFileToWrite + ".json");
            writer.write(jsonToWrite);
            writer.close();
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    // Method to read station schedule urls from the station json file by given station name
    // Retrieves the json file from C:\radioreminder\schedules\stations\<stationname>.json
    public static LinkedHashMap<String, String> ReadScheduleUrlsFromJson(String stationName) {
        stationName = functions_Strings.ReturnShortStationName(stationName);
        return ReturnLinkedHashMapFromJson(constants.schedulesStationsDir, stationName);
    }

    public static LinkedHashMap<String, String> ReadStationsFromJson(String locality) {
        return ReturnLinkedHashMapFromJson(constants.stationsDir, locality);
    }

    // Method to read the station files and return a linkedhashmap of station schedule urls by given locality
    public static LinkedHashMap<String, String> ReadStationScheduleUrlsByLocalityFromJson(String locality) {
        return ReturnLinkedHashMapFromJson(constants.stationsDir, locality);
    }

    // Method to return a linkedhashmap from a json file
    public static LinkedHashMap<String, String> ReturnLinkedHashMapFromJson(String jsonDirectory, String jsonFile) {
        LinkedHashMap<String, String> lhm = null;

        // Read the station schedules json and return a List of scheduleUrls
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();

        try {
            FileReader fileReader = new FileReader(jsonDirectory + jsonFile + ".json");
            BufferedReader buffered = new BufferedReader(fileReader);
            lhm = gson.fromJson(buffered, type);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return lhm;
    }

    // Method to return the schedule url from a json file by bbc schedule date
    public static String ReturnScheduleUrlFromJsonByBBCScheduleDate(String stationName, String bbcScheduleDate) {
        String stationScheduleUrl = null;
        stationName = functions_Strings.ReturnShortStationName(stationName);
        LinkedHashMap<String, String> listScheduleUrls = null;

        // Read the station schedules json and return a List of scheduleUrls
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();

        try {
            FileReader fileReader = new FileReader(constants.schedulesStationsDir + stationName + ".json");
            BufferedReader buffered = new BufferedReader(fileReader);
            listScheduleUrls = gson.fromJson(buffered, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        stationScheduleUrl = listScheduleUrls.get(bbcScheduleDate);
        return stationScheduleUrl;
    }

    // This method takes a hashmap and prints out the json
    public static boolean JSONToMap(HashMap mapTo) {
        Gson gson = new Gson();
        String json = gson.toJson(mapTo);

        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
        return false;
    }
}
